package com.carambatv.android.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.carambatv.android.R;
import com.carambatv.android.adapter.VideoAdapter;
import com.carambatv.android.db.VideoColumns;
import com.carambatv.android.db.VideoQuery;
import com.carambatv.android.model.VideoObject;
import com.carambatv.android.service.UpdateService;
import com.carambatv.android.utils.Config;
import com.carambatv.android.utils.DetachableResultReceiver;
import com.carambatv.android.utils.DetachableResultReceiver.Receiver;
import com.carambatv.android.utils.NotifyingAsyncQueryHandler;
import com.carambatv.android.utils.YtubeProcessor;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class VideosActivity extends GAActivity implements Receiver, OnItemClickListener, OnScrollListener, OnClickListener,
		NotifyingAsyncQueryHandler.AsyncQueryListener {

	private DetachableResultReceiver receiver;
	private ProgressDialog progress;
	private ListView listView;
	private VideoAdapter adapter;
	private Button button;
	public static final String ADS_ID = "a14f5266eb813cb";
	private static int limit = Config.step_limit;
	private boolean visibility = true;
	private String type;
	private TextView title;
	private NotifyingAsyncQueryHandler mHandler;
	private Cursor mCursor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		listView = (ListView) findViewById(R.id.list);
		title = (TextView) findViewById(R.id.title);
		button = (Button) findViewById(R.id.show_more);
		button.setOnClickListener(this);

		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		type = getIntent().getStringExtra(Config.TYPE);
		String title_value = getIntent().getStringExtra(Config.TITLE);
		title.setText(title_value);

		progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
		mHandler.cancelOperation(VideoQuery._TOKEN);
		mHandler.startQuery(VideoQuery._TOKEN, null, VideoObject.CONTENT_URI, VideoQuery.PROJECTION, VideoColumns.TYPE.getName() + "=?", new String[] { type },
				VideoObject.DATE_SORT + " limit " + limit);

		updateList(1, 2 * Config.step_limit);

		LinearLayout layout = (LinearLayout) findViewById(R.id.ads);
		AdView adView = new AdView(this, AdSize.BANNER, ADS_ID);
		layout.addView(adView);
		AdRequest request = new AdRequest();
		// request.setTesting(true);
		adView.loadAd(request);

	}

	@Override
	protected void onResume() {
		if (mCursor != null) {
			mCursor.requery();
		}
		super.onResume();
	}

	private void updateList(int start, int count) {
		Intent upfateIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateService.class);
		upfateIntent.putExtra(UpdateService.EXTRA_STATUS_RECEIVER, receiver);
		upfateIntent.putExtra(UpdateService.EXTRA_REQUEST_CODE, Config.YTUBE);
		upfateIntent.putExtra(Config.TYPE, type);
		upfateIntent.putExtra(Config.START, start);
		upfateIntent.putExtra(Config.COUNT, count);
		startService(upfateIntent);
	}

	@Override
	protected void onDestroy() {
		limit = Config.step_limit;
		super.onDestroy();
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateService.STATUS_RUNNING:
			break;
		case UpdateService.STATUS_ERROR:
			if (progress != null)
				progress.dismiss();
			break;
		case UpdateService.STATUS_FINISHED:
			if (mCursor != null) {
				mCursor.requery();
			}
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

		VideoAdapter adapter = (VideoAdapter) adapterView.getAdapter();
		Cursor cursor = adapter.getCursor();

		if (cursor != null && cursor.moveToPosition(position)) {
			String id_video = cursor.getString(VideoQuery.ID_VIDEO);
			Log.e(id_video, id_video);
			try {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id_video));
				startActivity(intent);
			} catch (Exception e) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://details?id=com.google.android.youtube"));
				try {
					startActivity(intent);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.show_more:

			button.setVisibility(View.GONE);
			limit += Config.step_limit;
			if (limit > YtubeProcessor.total) {
				visibility = false;
			} else {
				updateList(limit, Config.step_limit);
			}
			mHandler.cancelOperation(VideoQuery._TOKEN);
			mHandler.startQuery(VideoQuery._TOKEN, null, VideoObject.CONTENT_URI, VideoQuery.PROJECTION, VideoColumns.TYPE.getName() + "=?",
					new String[] { type }, VideoObject.DATE_SORT + " limit " + limit);

			break;

		default:
			break;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		button.setVisibility((visibility && totalItemCount - firstVisibleItem < 3) ? View.VISIBLE : View.GONE);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case VideoQuery._TOKEN:
			if (cursor != null) {
				if (mCursor != null) {
					stopManagingCursor(mCursor);
					mCursor = null;
				}
				mCursor = cursor;
				if (progress != null && mCursor.getCount() != 0)
					progress.dismiss();
				startManagingCursor(mCursor);
				if (adapter == null) {
					adapter = new VideoAdapter(VideosActivity.this, mCursor);
					listView.setAdapter(adapter);
				} else {
					adapter.changeCursor(mCursor);
					adapter.notifyDataSetChanged();
				}
			}
			break;
		default:
			break;
		}

	}

}